﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using Microsoft.Search.Interop;
using Misuzilla.Crigate.Handler;

namespace Misuzilla.Crigate.Handlers.WindowsSearchHandler
{
    [IsolatedAppDomain]
    [ActivateContext(ActivateContexts.SessionStarted)]
    public class WindowsSearchHandler : MarshalByRefObject, IHandler
    {
        private Console _console;

        #region IHandler メンバ
        public void Initialize(Session session)
        {
            _console = new Console();
            _console.Initialize(session);
            _console.Attach("#Search", typeof(SearchContext), true);
        }

        public void Uninitialize()
        {
            _console.Detach();
        }
        #endregion

        #region IDisposable メンバ
        public void Dispose()
        {
        }
        #endregion
    }

    public class SearchContext : Context
    {
        public override bool OnCallMissingCommand(string commandName, string rawInputLine)
        {
            Console.NotifyMessage("検索しています...");
            CSearchManager manager = new CSearchManager();
            CSearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");
            CSearchQueryHelper queryHelper = catalogManager.GetQueryHelper();
            queryHelper.QuerySelectColumns = "System.Title, System.ItemName, System.ItemPathDisplay, System.Search.AutoSummary";
            queryHelper.QueryMaxResults = 20;
            String sqlQuery = queryHelper.GenerateSQLFromUserQuery(rawInputLine);

            using (OleDbConnection connection = new OleDbConnection(queryHelper.ConnectionString))
            {
                connection.Open();
                using (OleDbCommand cmd = new OleDbCommand(sqlQuery))
                using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(cmd))
                {
                    DataSet dataSet = new DataSet();
                    dataAdapter.SelectCommand.Connection = connection;
                    dataAdapter.Fill(dataSet);
                    var results = from DataRow row in dataSet.Tables[0].Rows
                                  let summary = row["System.Search.AutoSummary"].ToString()
                                  let shortSummary = summary.Substring(0, Math.Min(summary.Length, 20))
                                  select String.Format("\u00031\u0002{0}\u000f | {1} | {2}...", row["System.ItemName"], row["System.ItemPathDisplay"], shortSummary);

                    Console.NotifyMessage(String.Format("{0}件が見つかりました。", dataSet.Tables[0].Rows.Count));
                    foreach (var result in results)
                        Console.NotifyMessage(result.Replace("\r", "").Replace("\n", ""));
                }
            }
            
            return true;
        }
    }
}
